#include "StdSem.h"
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <sys/types.h>
#include <unistd.h>
#include <sys/wait.h>
#include <fcntl.h>
#include <sys/stat.h>
#include <signal.h>
#include <StdFile.h>
#include <sys/sem.h>

struct StdSem
{
    int SemID;
};

Sem *InitSem(const char *pathName, int proj_id)
{
    Sem *s = (Sem*)malloc(sizeof(Sem));
    if(s == NULL)
        return NULL;
    
    int key = ftok(pathName,proj_id);
    if(key < 0)
    {
        perror("ftok");
        free(s);
        return NULL;
    }

    //信号量ID,IPC键值、信号量数量、权限
    s->SemID = semget(key,1,IPC_CREAT | 0777);
    if(s->SemID < 0)
    {
        perror("SEMGET");
        free(s);
        return NULL;
    }

    //信号量控制，0下标,设定信号量值为1
    if(semctl(s->SemID,0,SETVAL,1) < 0)
    {
        perror("semctl");
        free(s);
        return NULL;
    }
    return s;
}

void SemPV(int semID, int op)
{
    struct sembuf semb;
    semb.sem_num = 0;
    semb.sem_op = op;
    semb.sem_flg = SEM_UNDO;
    semop(semID,&semb,1);
}
void Semp(Sem *s)
{
    SemPV(s->SemID,-1);
}

void Semv(Sem *s)
{
    SemPV(s->SemID,1);
}

void ClearSem(Sem *s)
{
    if(s == NULL)
        return;
    semctl(s->SemID,0,IPC_RMID,NULL);
    free(s);
}
